package com.lee.common.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.lee.common.R;


/**
 * @ProjectName: YunAnXin
 * @Author: RICO
 * @Time: 2020/11/20 15:40
 * @Description:
 */
public class EditTextPassword extends androidx.appcompat.widget.AppCompatEditText {

    private boolean mIsShow = false;

    public interface DrawableRightListener {
        void onDrawableRightClick();
    }

    private DrawableRightListener mRightListener;

    public void setDrawableRightListener(DrawableRightListener listener) {
        this.mRightListener = listener;
    }

    private Drawable drawableRight;

    final int DRAWABLE_RIGHT = 2;

    public EditTextPassword(Context context) {
        super(context);
        init();
    }

    public EditTextPassword(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public EditTextPassword(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        drawableRight = getCompoundDrawables()[DRAWABLE_RIGHT];
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            //判断点击是否落在rightDrawable中
            if (x > getWidth() - getTotalPaddingRight() && x < getWidth() && y > 0 && y < getHeight()) {
                int pos = getSelectionStart();
                onDrawableRightClick();
                this.setSelection(pos);
            }
        }
        return super.onTouchEvent(event);
    }

    private void onDrawableRightClick() {
        if (mIsShow) {
            setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_eye, 0);
            setTransformationMethod(HideReturnsTransformationMethod.getInstance());

        } else {
            setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_open_eye, 0);
            setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        mIsShow = !mIsShow;
    }
}
